<?php

namespace App\Http\Controllers\Innerend;

use App\Http\Controllers\Controller;
use App\Jobs\TaskJob;
use App\Manage\Html\AdminForm;
use App\Manage\Html\AdminList;
use App\Models\Admin;
use App\Models\News;
use App\Models\SiteType;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redirect;

class BaseController extends Controller
{
    protected $adminList;
    protected $adminForm;

    protected $model;
    protected $error;
    protected $myUser;

    // 同步：进入列表，展示列表表单
    // 异步：进入列表，根据统计在展示表单
    protected $is_sync = true;

    // 初始化
    public function initialize()
    {
        $user = $this->myUser();
        $opt  = $this->optLogic();
        // 权限判断 通过控制器来判断
        $controller   = $opt->getData('controller', 'home', 'trim');
        $action       = $opt->getData('action', 'home', 'trim');
        $this->myUser = $user;

        $opt->assign('myUser', $user);
        $opt->assign('controller', $controller);
        $opt->assign('back_site_name', '复旦复华后台管理系统');
        $opt->assign('action', $action);
        $opt->assign('init_url', Url('/innerend/'.$controller.'/lists'));
        $opt->assign('formUrl', url('/innerend/'.$controller.'/on-'.($action == 'add' ? 'add' : 'edit')));

        // 所有的人都可以操作的控制器：测试，登录，
        if(!in_array($controller, ['account', 'test', 'search', 'deal',])){
            // TODO 必须登录
            if(empty($user)){
                if($this->request->ajax()){
                    $this->throwIf(true, '请登录后在操作！');
                } else{
                    $this->jumpLogin();
                }
            }

            // 设置目录
            $this->menus();

            // TODO 公共权限
            //   发布文章快讯新鲜事：可以选择用户，选择话题
            $con_act = $controller.'_'.$action;
            $hasRole = in_array($con_act, ['user_lists', 'topic_lists',]);

            // 判断权限：是否含有当前控制器 => 如果不存在 则没有权限
            // 如果是1 超级管理员 所有权限都有
            /*if(($user['uid'] != 1) || empty($hasRole)){
                // 权限处理
                // $role = $user['role'] ?? '[]';
                // $role = json_decode($role, true);
                $role = array_column($user['role'], 'role');

                // 其中几个特殊控制器
                $all         = [];
                $controllers = ['point', 'business', 'dispatch', 'abroad', 'news', 'author', 'image',];
                foreach($user['role'] as $item){
                    $_role = $item['role'];
                    if(in_array($_role, $controllers)){
                        $all[] = $_role.'-cate';
                        $all[] = $_role.'-article';
                        $all[] = 'comment';
                    }
                    // 栏目中，获取文章列表
                    if($_role == 'cate'){
                        $all[] = 'article';
                    }
                    $all[] = $_role;
                }

                $this->throwIf(!in_array($controller, $all), '你没有该操作权限！！');
            }*/
            /*if($user['uid'] == 1){
                $this->throwIf(!$user['hasRole'], '你没有该操作权限！！');
            }*/
        }
    }

    // 获取用户以及权限
    protected function myUser()
    {
        $user = $this->optLogic()->request()->session()->get('innerend_user');
        if(empty($user)){
            $user = Cookie::get('innerend_user');
            if(empty($user)){
                return [];
            }

            $user = json_decode($user, true);
        }
        if(empty($user)){
            return [];
        }

        $admin = new Admin();
        $info  = $admin->isCache(true)->oneFind(['id' => $user['id']]);
        $info  = is_object($info) ? $info->toArray() : $info;
        if(empty($info)){
            //$this->jumpLogin('登录过期，请重新登录！！');
            return [];
        }
        if($info['status'] != 1){
            // TODO 如果用户被禁用，应该清空 cookie 不然会一直进入循环请求
            //$this->jumpLogin('用户被禁用！！');
            return [];
        }
        // 组合
        $info['uid'] = $info['id'];
        $hasRole     = true;

        //makeRoles($roles, $is_parent = true);
        // 判断权限
        /*if($info->uid != 1){
            $roles      = $info->getRawOriginal('role');
            $roles      = is_string($roles) ? json_decode($roles) : $roles;
            $controller = strtolower($this->controller);
            $action     = strtolower($this->action);
            $cate_id    = $this->getData('cate_id', 0, 'intval');    // 一些栏目权限
            // TODO 权限判断1、根据操作控制器来判断
            // TODO 权限判断2、文章列表，根据控制与栏目id判断
            // TODO 权限判断3、两个特殊栏目：草稿与头条的文章列表，根据控制与操作方法header和draft来判断
            $param = $cate_id;
            if(in_array($action, ['header', 'draft'])){
                $param = $action;
            }

            $hasRole = $admin->checkRole($roles, $controller, $param);
        }
        // 重新组合
        $info->hasRole = $hasRole;*/
        $this->optLogic()->setUser($info);

        return $info;
    }

    // 加载模板输出
    protected function dispaly($template, $vars = [])
    {
        return $this->optLogic()->dispaly('innerend/'.$template, $vars, false);
    }

    // 返回数据
    protected function assign($name, $value = '')
    {
        return $this->optLogic()->assign($name, $value);
    }

    // 已经传递的数据
    protected function getAssign($name, $value = '')
    {
        return $this->optLogic()->getAssign($name, $value);
    }

    // 转跳页面
    protected function jumpTo($url, $message = '')
    {
        return $this->dispaly('jump', ['url' => $url, 'message' => $message,]);
    }

    // 展示转跳登录
    protected function jumpLogin($msg = '请重新登录在操作！')
    {
        // 删除cookie后需要重新定向
        $cookie = Cookie::forget('user');
        $url    = htmlUrl('innerend/account/login');
        $url    = Url('innerend/account/login');

        die($this->jumpTo($url, $msg));
        //return Redirect::secure($url)->withCookie($cookie);
    }

    // 展示目录
    protected function menus()
    {
        // &#xe62e;  &#xe62b;  &#xe616;  &#xe68a;  &#xe627;
        $menus = [
            [
                'title' => '基本菜单',
                'icon'  => '&#xe62e;',
                'child' => [
                    ['title' => '后台首页', 'url' => '/home/welcome',],
                    ['title' => '管理员', 'url' => '/admin/lists',],
                    //['title' => '角色管理', 'url' => '/home/welcome',],
                ],
            ],
            /*[
                'title' => '管理员管理',
                'icon'  => '&#xe62b;',
                'child' => [
                    ['title' => '管理员', 'url' => '/admin/lists',],
                    //['title' => '角色管理', 'url' => '/home/welcome',],
                ],
            ],*/
            [
                'title' => '用户管理',
                'icon'  => '&#xe616;',
                'child' => [
                    ['title' => '用户列表', 'url' => '/user/lists',],
                    ['title' => '认证会员', 'url' => '/user-verify/lists',],
                ],
            ],
            [
                'title' => '内容管理',
                'icon'  => '&#xe616;',
                'child' => [
                    ['title' => '文章管理', 'url' => '/news/lists',],
                    ['title' => '快讯管理', 'url' => '/dispatch/lists',],
                    ['title' => '长短文管理', 'url' => '/fresh/lists',],
                ],
            ],
            [
                'title' => '运营管理',
                'icon'  => '&#xe616;',
                'child' => [
                    ['title' => '话题管理', 'url' => '/topic/lists',],
                    ['title' => '长短文投诉管理', 'url' => '/fresh-complain/lists',],
                    ['title' => '意见反馈', 'url' => '/site-feedback/lists',],
                ],
            ],
            [
                'title' => '访谈管理',
                'icon'  => '&#xe616;',
                'child' => [
                    ['title' => '线下活动', 'url' => '/fangtan/lists?is_online=0',],
                    ['title' => '在线直播', 'url' => '/fangtan/lists?is_online=1',],
                ],
            ],
            [
                'title' => '系统设置',
                'icon'  => '&#xe616;',
                'child' => [
                    ['title' => '媒体认证分类', 'url' => '/site-type/lists?channel=user_medium',],
                    ['title' => '专家认证分类', 'url' => '/site-type/lists?channel=user_expert',],
                    ['title' => '用户擅长领域', 'url' => '/site-type/lists?channel=good_areas',],
                    ['title' => '长短文投诉类型', 'url' => '/site-type/lists?channel=fresh_complain',],
                    ['title' => '新闻要闻分类', 'url' => '/site-cate/lists',],
                    ['title' => '广告管理', 'url' => '/site-adv/lists',],
                    ['title' => '话题分类', 'url' => '/topic-cate/lists',],
                ],
            ],
            // about:关于深蓝,privacy:隐私保护,service:服务协议,customer:客服中心,gold:积分说明,link:友情链接,contact:联系深蓝
            [
                'title' => '站点信息',
                'icon'  => '&#xe616;',
                'child' => [
                    ['title' => '关于深蓝', 'url' => '/site-info/content?key=about',],
                    ['title' => '隐私政策', 'url' => '/site-info/content?key=privacy',],
                    ['title' => '用户协议', 'url' => '/site-info/content?key=service',],
                    ['title' => '客服中心', 'url' => '/site-info/content?key=customer',],
                    ['title' => '深蓝币说明', 'url' => '/site-info/content?key=gold',],
                    ['title' => '友情链接', 'url' => '/site-info/content?key=link',],
                    ['title' => '联系深蓝', 'url' => '/site-info/content?key=contact',],
                ],
            ],
        ];

        $this->assign('menus', $menus);
    }

    // 列表页面
    protected function adminList()
    {
        if(empty($this->adminList)){
            $controller      = $this->optLogic()->getData('controller', 'home', 'trim');
            $this->adminList = new AdminList('innerend', $controller);
        }

        return $this->adminList;
    }

    // 表单页面
    protected function adminForm()
    {
        if(empty($this->adminForm)){
            $controller      = $this->optLogic()->getData('controller', 'home', 'trim');
            $this->adminForm = new AdminForm('innerend', $controller);
        }

        return $this->adminForm;
    }

    ###############################################################################################
    ## 页面展示
    ###############################################################################################
    // 列表（如果是树状的时候，可以重写该方法就好，页面不用处理）
    public function lists()
    {
        $this->list_search();
        $this->listTopButton();

        $this->assign('request', $this->optLogic()->getData());
        $this->assign('fields', $this->list_fields());

        // 操作
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        // 执行
        $result = $manage->onCount();

        // 首页直接展示的时候 页面展示比较乱 且 翻页不成功
        if($this->is_sync){
            // 获取列表
            $lists = $manage->onLists();
            if($lists === false){
                return $this->error($manage->getError());
            }
            // 列表展示
            $trList = $this->listTable($lists);
            // 组合
            $result['list'] = $lists;
            $result['tr']   = $trList;
        }


        return $this->dispaly('lists', $result);
    }

    // 添加
    public function add()
    {
        $formHtml = $this->formTable();

        return $this->dispaly('form', ['formHtml' => $formHtml]);
    }

    // 修改
    public function edit()
    {
        $formHtml = $this->formTable();

        return $this->dispaly('form', ['formHtml' => $formHtml]);
    }

    // 列表搜索
    protected function list_search()
    {
        $request = $this->optLogic()->getData();
        $form    = $this->adminList();
        $keyword = $form->formInput('keyword', $request['keyword'] ?? '', '关键字');
        $search  = ['keyword' => $keyword,];  // keyword
        $this->assign('search', $search);

        $searchHide = ['channel'];
        $this->assign('searchHide', []);
    }

    ###############################################################################################
    ## 数据操作
    ###############################################################################################
    // 查询统计
    public function onCount()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onCount();

        return $this->success($result);
    }

    // 返回列表数据
    public function onLists()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $lists = $manage->onLists();
        if($lists === false){
            return $this->error($manage->getError());
        }

        $trList = $this->listTable($lists);
        $result = ['tr' => $trList, 'list' => $lists];

        return $this->success($result);
    }

    // 删除
    public function onDelete()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onDelete();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success();
    }

    // 软删除
    public function onSoft()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onSoft();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success();
    }

    // 启用禁用
    public function onStatus()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onStatus();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success([], '更新成功！');
    }

    // 修改
    public function onEdit()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onEdit();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success();
    }


    // 添加
    public function onAdd()
    {
        $manage = $this->checkManage($this->model);
        if($manage === false){
            return $this->error($manage->getError());
        }

        $result = $manage->onAdd();
        if($result === false){
            return $this->error($manage->getError());
        }

        return $this->success();
    }


    ###############################################################################################
    ## 待删除
    ###############################################################################################

    // 待删除（以前的初始化）
    public function _initialize2()
    {
        // 获取用户信息
        $user = $this->myUser();

        // 权限判断 通过控制器来判断
        $controller   = strtolower($this->controller);
        $this->myUser = $user;
        $this->assign('myUser', $user);
        $this->assign('controller', $controller);
        $this->assign('action', $this->action);
        $this->assign('init_url', url('/innerend/'.$controller.'/lists'));


        // 所有的人都可以操作的控制器：测试，登录，
        if(!in_array($controller, ['account', 'test', 'search', 'deal', 'spider',])){
            if(empty($user)){
                $this->jumpLogin();
            }
            // 设置目录
            $this->menus();

            // TODO 公共权限
            //   发布文章快讯新鲜事：可以选择用户，选择话题
            $con_act = $controller.'_'.$this->action;
            $hasRole = in_array($con_act, ['user_lists', 'topic_lists',]);

            // 判断权限：是否含有当前控制器 => 如果不存在 则没有权限
            // 如果是1 超级管理员 所有权限都有
            if(($user['uid'] != 1) || empty($hasRole)){
                // 权限处理
                /*// $role = $user['role'] ?? '[]';
                // $role = json_decode($role, true);
                $role = array_column($user['role'], 'role');

                // 其中几个特殊控制器
                $all         = [];
                $controllers = ['point', 'business', 'dispatch', 'abroad', 'news', 'author', 'image',];
                foreach($user['role'] as $item){
                    $_role = $item['role'];
                    if(in_array($_role, $controllers)){
                        $all[] = $_role.'-cate';
                        $all[] = $_role.'-article';
                        $all[] = 'comment';
                    }
                    // 栏目中，获取文章列表
                    if($_role == 'cate'){
                        $all[] = 'article';
                    }
                    $all[] = $_role;
                }

                $this->throwIf(!in_array($controller, $all), '你没有该操作权限！！');*/
            }
            /*if($user['uid'] == 1){
                $this->throwIf(!$user['hasRole'], '你没有该操作权限！！');
            }*/
        }
    }

    // 判断操作模型是否存在
    protected function _checkModel($model = '')
    {
        $this->throwIf(empty($model), '请指定数据模型！！');
        // 模型 与 查询
        $model = 'App\Models\\'.ucwords($model);
        if(!class_exists($model)){
            $request = request();
            $real_ip = $request->getClientIp();
            $test_ip = env('TEST_IP');
            $this->throwIf(true, '模型不存在！！');

            //$this->throwIf($real_ip == $test_ip, '模型不存在！！');

            return false;
        }

        return new $model;
    }

    // 查找
    public function _onShow()
    {
        if(empty($this->id)){
            return [];
        }

        $where = ['id' => $this->id];
        $model = $this->checkModel($this->model);
        $info  = $model->isCache(true)->oneFind($where);
        $this->throwIf($info === false, $model->getError());

        $info = is_object($info) ? $info->toArray() : $info;
        $this->assign('info', $info);

        return $info;
    }


    // ajax改变某个字段的值
    protected function _changeField($_field, $_value)
    {
        $id = $this->id;
        if(empty($id) || empty($_field) || ($_value === '')){
            return $this->error('请指定修改参数！！');
        }

        // 执行
        $deal   = $this->checkModel($this->model);
        $result = $deal->oneEdit(['id' => $id], [$_field => $_value]);
        $this->throwIf($result === false, $deal->getError());

        return $this->success([], '更新成功！');
    }

    // 改变（直接修改，软删除，改变状态，排序）
    public function _onEdit()
    {
        $this->throwIf(empty($this->id), '请指定修改的ID编号！');
        $data = $this->_before_edit();
        $this->throwIf($data === false, $this->error);

        // 组合数据
        $where = $this->editWhere();
        $data  = $this->filterNull($data);
        $model = $this->checkModel($this->model);
        $data  = $model->checkData($data, $where);
        $this->throwIf($data === false, $model->getError());

        // 验证
        $result = $model->checkRules($data, 'edit');
        $this->throwIf($result === false, $model->getError());


        $result = $model->oneEdit($where, $data);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 树状
    public function _onAdd()
    {
        $data = $this->_before_add();
        $this->throwIf($data === false, $this->error);

        // 组合数据
        $data  = $this->filterNull($data);
        $model = $this->checkModel($this->model);
        $data  = $model->checkData($data);
        $this->throwIf($data === false, $model->getError());

        // 验证
        $result = $model->checkRules($data, 'add');
        $this->throwIf($result === false, $model->getError());

        // 保存
        $result = $model->oneAdd($data);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    ###############################################################################################

    // 判断操作模型是否存在
    protected function checkManage($manage = '')
    {
        $this->throwIf(empty($manage), '请指定操作！！');
        // 模型 与 查询
        $manage = 'App\Manage\\'.ucwords($manage).'Manage';
        if(!class_exists($manage)){
            $request = request();
            $real_ip = $request->getClientIp();
            $test_ip = env('TEST_IP');
            $this->throwIf(true, '操作不存在！！');

            //$this->throwIf($real_ip == $test_ip, '模型不存在！！');

            return false;
        }

        return new $manage;
    }

    // 抛出异常
    protected function throwIf($condition, $msg, $code = 400)
    {
        if($condition){
            throw new \RuntimeException($msg, $code);
        }
    }


}


